//
//  RTTabBar.swift
//  Weibo
//
//  Created by Brisinga on 16/3/2.
//  Copyright © 2016年 Root. All rights reserved.
//

import UIKit

class RTTabBar: UITabBar {

    
    var composeButtonClickClosure:(()->())?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    // 初始化内部空间
   private func setupUI () {
    
        addSubview(composeButton)
     }
    
    
    
    // 布局内部空间
    override func layoutSubviews() {
        super.layoutSubviews()
        
        composeButton.center = CGPoint(x: center.x, y: frame.height*0.5)
        
        let itemWidth: CGFloat = frame.width * 0.2
        
        var index: Int = 0
        
        for childView in subviews {
            
            if childView.isKindOfClass(NSClassFromString("UITabBarButton")!) {
                
                let itemX = CGFloat(index) * itemWidth
                
                childView.frame.origin.x = itemX
                childView.frame.size.width = itemWidth
                
                index++
                
                if index == 2 {
                    
                    index += 1
                }
            }
        }
    }
    
    // 按钮点击事件
    @objc private func composeButtonDidClick() {
    
        composeButtonClickClosure?()
    }
    
    
    // 懒加载按钮
   private lazy var composeButton: UIButton = {
        
        let compose = UIButton()
    
        compose.addTarget(self, action: "composeButtonDidClick", forControlEvents: .TouchUpInside)
        
        compose.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: .Normal)
        
        compose.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: .Highlighted)
        
        compose.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: .Normal)
        
        compose.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: .Highlighted)
        
        compose.sizeToFit()
        
        return compose
    }()
}
